Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
addEventListener vs onclick
addEventListener
and onclick
are equivalent.
However, we can use addEventListener
to listen to events from more than one DOM element.
For instance, if we have:
element.addEventListener('click', () => {
//...
}, false);
Then we can listen to the click
event of element
.
We can also write:
element.onclick = () =>
//...
}
which does the same thing.
We can use the event
object to listen to multiple events.
For example, we can write:
element.addEventListener('click', (event) => {
//...
}, false);
Then we can use the event
object to get the event data from elements that’s a child of element
and check for actions.
Strip all Non-Numeric Characters from String
We can strip all non-numeric characters from a string with the replace
method.
For example, we can write:
const s = "123 abc".replace(/[^\d.-]/g, '');
We use the ^\d
to look for all non-numeric characters.
Then we add the g
tag to search for all instances of the pattern in the string.
How to Sort an Array by a Date Property
To sort an array by a Date
property, we can use the sort
method.
For instance, we can write:
array.sort((a, b) => {
return new Date(b.date) - new Date(a.date);
});
We turn the date strings into Date
instances, then we can subtract them to get the sort order.
We can do that since the subtraction operator will convert the Date
instances into timestamps, which are integers.
Sorting Object Property by Values
To sort object properties by values, we can sort the keys by their values with the sort
method.
For instance, we can write:
const list = {"baz": 200, "me": 75, "foo": 116, "bar": 15};
keysSorted = Object.keys(list).sort((a, b) => {
return list[a] - list[b];
})
console.log(keysSorted);
We have the list
object.
And we get the keys as an array with Object.keys
.
Then we can call sort
on the returned array.
Moment.js Transform to Date Object
We can use the toDate
method to transform a moment object into a Date
object.
For instance, we can write:
moment().toDate();
Test for Existence of Nested JavaScript Object Key
We can check for a key with the recursive function.
For instance, we can write:
const checkNested = (obj, level, ...rest) => {
if (obj === undefined) {
return false;
}
if (rest.length === 0 && obj.hasOwnProperty(level)) {
return true;
}
return checkNested(obj[level], ...rest)
}
We check if obj
is undefined
and return false
if it is since it’s undefined
before we got to the end of the path.
Otherwise, we check that there are no arguments left and check if the property with the key level
exists.
If that exists, then we return true
.
Otherwise, we call the checkNested
function again by moving on to the lower level.
So we can call it by writing:
checkNested(foo, 'level1', 'level2', 'bar');
to check if foo.level1.level2.bar
exists.
To make our lives easier, we can also use the ?.
optional chaining operator:
const value = obj?.level1?.level2?.level3
It’ll just return undefined
if any intermediate level doesn’t exist.
Playing Audio with Javascript
We can use the play
method of an audio element to play audio with JavaScript.
For instance, we can write:
const audio = new Audio('audio.mp3');
audio.play();
or:
document.getElementById('audioPlayer').play();
Defining a Class in JavaScript
We can define a class in 2 ways.
We can create a constructor function or use a class syntax.
For instance, we can write:
function Person(name) {
this.name = name;
}
to create a Person
constructor.
Then to add methods, we write:
Person.prototype.greet = function() {
console.log(`hello ${this.name}`);
}
We can use the class syntax to do the same thing:
class Person {
constructor(name) {
this.name = name;
}
greet``() {
console.log(`hello ${ this.name }`);
}
}``
We define instance methods in the class instead of adding a property to prototype
.
It’s cleaner and static analysis can check its syntax.
It’s also easier to understand for people coming from class-based languages.
Both ways are the same.
Conclusion
We can define classes in multiple ways.
Also, we can test for the existence of nested object keys by using the optional chaining operator or our own function.
There are various ways to sort things.